/**
 * 存储错误辅助工具
 */
import { StorageErrorCode, type StorageError } from './types'

// 重新导出供外部使用
export { StorageErrorCode, type StorageError } from './types'

export const createStorageError = (
  code: StorageErrorCode,
  message: string,
  cause?: unknown
): StorageError => ({
  code,
  message,
  cause
})

export const mapExceptionToStorageError = (error: unknown): StorageError => {
  if (typeof window === 'undefined') {
    return createStorageError(StorageErrorCode.UNKNOWN, '运行环境不支持LocalStorage', error)
  }

  if (error instanceof DOMException) {
    if (error.name === 'QuotaExceededError' || error.code === 22 || error.code === 1014) {
      return createStorageError(StorageErrorCode.QUOTA_EXCEEDED, 'LocalStorage容量已满', error)
    }

    return createStorageError(StorageErrorCode.UNKNOWN, error.message || 'LocalStorage操作失败', error)
  }

  if (error instanceof Error) {
    return createStorageError(StorageErrorCode.UNKNOWN, error.message, error)
  }

  return createStorageError(StorageErrorCode.UNKNOWN, 'LocalStorage操作发生未知错误', error)
}
